<?php
require_once(dirname(__FILE__).'/../common.inc.php');
require_once(DEDEINC.'/image.func.php');

if(is_file(DEDEINC.'/json.class.php'))
{
	require_once(DEDEINC.'/json.class.php');
	$json = new Services_JSON();
}else
{
	exit('{"error":1,"message":"file .\/include\/json.class.php not exists"}');
}

require_once(DEDEINC."/userlogin.class.php");
$cuserLogin = new userLogin();
if($cuserLogin->getUserID() <=0 )
{
	exit($json->encode(array('error' => 1, 'message' => 'action not allow')));
}

if(empty($dopost)) $dopost = '';
if(empty($urlValue)) $urlValue = '';
if(empty($imgsrcValue)) $imgsrcValue = '';

if($dopost=='upload')
{
		if(!is_uploaded_file($imgFile))
		{
			exit($json->encode(array('error' => 1, 'message' => 'no file have been upload')));
		}
		else
		{
			$imgFile_name = ${'imgFile_name'};
			$imgFile_type = ${'imgFile_type'};
		}
	
		if(!eregi("\.(jpg|gif|png|bmp|pjpeg|jpeg|wbmp)$",$imgFile_name)) {
			exit($json->encode(array('error' => 1, 'message' => 'file type error')));
		}
		
		$sparr = Array('image/pjpeg','image/jpeg','image/gif','image/png','image/xpng','image/wbmp');
		$imgFile_type = strtolower(trim($imgFile_type));
		if(!in_array($imgFile_type,$sparr)) {
			exit($json->encode(array('error' => 1, 'message' => 'file type error')));
		}

		$nowtme = time();
		$y = MyDate($cfg_addon_savetype, $nowtme);
		$filename = $cuserLogin->getUserID().'_'.MyDate('ymdHis',$nowtme);
		
		if(!is_dir($cfg_basedir.$cfg_image_dir."/$y"))
		{
			MkdirAll($cfg_basedir.$cfg_image_dir."/$y", $cfg_dir_purview);
			CloseFtp();
		}
	
		$fs = explode('.', $imgFile_name);
		if(eregi("php|asp|pl|shtml|jsp|cgi", $fs[count($fs)-1])) {
			exit($json->encode(array('error' => 1, 'message' => 'file type error')));
		}
	
		$bfilename = $cfg_image_dir."/$y/".$filename.".".$fs[count($fs)-1];
		$dbbigfile = $filename.".".$fs[count($fs)-1];
		$fullfilename = $cfg_basedir.$bfilename;
	
		if(file_exists($fullfilename)) {
			if($cfg_multi_site=='N')
			{
				exit($json->encode(array('error' => 0, 'url' => $bfilename)));
			}else
			{
				exit($json->encode(array('error' => 0, 'url' => $cfg_basehost.$bfilename)));
			}
		}

		@move_uploaded_file($imgFile,$fullfilename);

		$imgsrcValue = $bfilename;
		$urlValue = $bfilename;
		$info = '';
		$bsizes = getimagesize($fullfilename,$info);
		$bimgwidthValue = $bsizes[0];
		$bimgheightValue = $bsizes[1];
		$bimgsize = filesize($fullfilename);
	
		$inquery = "INSERT INTO `#@__uploads`(title,url,mediatype,width,height,playtime,filesize,uptime,mid)
    	VALUES ('{$dbbigfile}','$bfilename','1','$bimgwidthValue','$bimgheightValue','0','{$bimgsize}','{$nowtme}','".$cuserLogin->getUserID()."');";
		$dsql->ExecuteNoneQuery($inquery);
		$fid = $dsql->GetLastID();
		AddMyAddon($fid, $bfilename);

		if(file_exists($fullfilename)) {
			require_once(DEDEDATA."/mark/inc_photowatermark_config.php");
			if(in_array($imgFile_type,$cfg_photo_typenames) && isset($photo_markup) && $photo_markup==1)
			{
				WaterImg($fullfilename,'up');
			}			
			
			if($cfg_multi_site=='N')
			{
				exit($json->encode(array('error' => 0, 'url' => $bfilename)));
			}else
			{
				exit($json->encode(array('error' => 0, 'url' => $cfg_basehost.$bfilename)));
			}
		}else
		{
			exit($json->encode(array('error' => 1, 'message' => 'image can not be upload')));
		}
}

if($dopost=='manage')
{
	if(!TestAdmin()) exit();
	$root_path  = $cfg_basedir.$cfg_image_dir. '/';
	$root_url = $cfg_image_dir. '/';
	$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
	
	if (empty($path)) {
		$current_path = realpath($root_path) . '/';
		$current_url = $root_url;
		$current_dir_path = '';
		$moveup_dir_path = '';
	} else {
		$current_path = realpath($root_path) . '/' . $path;
		$current_url = $root_url . $path;
		$current_dir_path = $path;
		$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
	}

	$order = empty($order) ? 'name' : strtolower($order);

	if (preg_match('/\.\./', $current_path)) {
		echo 'Access is not allowed.';
		exit;
	}

	//最后一个字符不是/
	if (!preg_match('/\/$/', $current_path)) {
		echo 'Parameter is not valid.';
		exit;
	}
	//目录不存在或不是目录
	if (!file_exists($current_path) || !is_dir($current_path)) {
		echo 'Directory does not exist.';
		exit;
	}
	
	//遍历目录取得文件信息
	$file_list = array();
	if ($handle = opendir($current_path)) {
		$i = 0;
		while (false !== ($filename = readdir($handle))) {
			if ($filename{0} == '.') continue;
			$file = $current_path . $filename;
			if (is_dir($file)) {
				$file_list[$i]['is_dir'] = true; //是否文件夹
				$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
				$file_list[$i]['filesize'] = 0; //文件大小
				$file_list[$i]['is_photo'] = false; //是否图片
				$file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
			} else {
				$file_list[$i]['is_dir'] = false;
				$file_list[$i]['has_file'] = false;
				$file_list[$i]['filesize'] = filesize($file);
				$file_list[$i]['dir_path'] = '';
				$file_ext = strtolower(array_pop(explode('.', trim($file))));
				$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
				$file_list[$i]['filetype'] = $file_ext;
			}
			$file_list[$i]['filename'] = $filename; //文件名，包含扩展名
			$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
			$i++;
		}
		closedir($handle);
	}

	usort($file_list, 'cmp_func');
	
	$result = array();
	//相对于根目录的上一级目录
	$result['moveup_dir_path'] = $moveup_dir_path;
	//相对于根目录的当前目录
	$result['current_dir_path'] = $current_dir_path;
	//当前目录的URL
	$result['current_url'] = $current_url;
	//文件数
	$result['total_count'] = count($file_list);
	//文件列表数组
	$result['file_list'] = $file_list;
	//输出JSON字符串
	echo $json->encode($result);
}

function cmp_func($a, $b) {
	global $order;
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}
?>